<?php
namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Area extends Backend
{

    /**
     * Seniors模型对象
     * @var \app\admin\model\Seniors
     */
    protected $model = null;

    public function _initialize()
    {
        $this->model = new \app\admin\model\Area;
        parent::_initialize();

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        // 父级ID
        $pid = $ids ? $ids : 0;
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where                                       = [];
            // $where['pid'] = $pid;
            $list = db('area')->where($where)->where(['deletetime' => null])->limit($offset, $limit)->order('weigh DESC,id ASC')->select();
            Tree::instance()->init($list);
            $list = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
            // dd()
            $total  = db('area')->where($where)->where(['deletetime' => null])->count();
            $result = ["total" => $total, "rows" => $list];

            return json($result);
        }

        $this->assignconfig("ids", $pid);
        $this->assignconfig("area_add_son", $this->auth->check("area/add_son"));
        $this->assignconfig("area_edit", $this->auth->check("area/edit"));
        $this->assignconfig("area_del", $this->auth->check("area/del"));
        $this->assignconfig("area_volunteer", $this->auth->check("volunteer/area_volunteer"));
        $this->assignconfig("area_staff", $this->auth->check("staff/area_staff"));
        return $this->view->fetch();
    }
   
     public function indexs()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyValue')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
         
            $list                                        = $this->model
                ->where($where)
                ->where('pid','=',0)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add($ids = null)
    {
        // 父级ID
        $pid         = $ids;
        $parent_name = db('area')->where(['id' => $pid])->value('name');
        $this->view->assign("pid", $pid);
        $this->view->assign("parent_name", $parent_name);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (! $params['name']) {
                    $this->error('请填写地区名称');
                }
                $params['level'] = 1;
                if ($params['pid']) {
                    $level = db('area')->where(['id' => $params['pid']])->value('level');
                    if (! $level) {
                        $this->error('上级地区有误,请刷新页面');
                    }
                    $params['level'] = $level + 1;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    // $result = db('area')->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        // 父级ID
        $row = db('area')->where(['id' => $ids])->find();
        if (! $row) {
            $this->error(__('No Results were found'));
        }

        $pid         = $row['pid'];
        $parent      = db('area')->where(['id' => $pid])->find();
        $parent_name = $parent['name'];
        $parent_list = db('area')->where(['pid' => $parent['pid']])->select();
        // dd($parent_list);
        $this->view->assign("parent_list", $parent_list);
        $this->view->assign("pid", $pid);
        $this->view->assign("parent_name", $parent_name);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (! $params['name']) {
                    $this->error('请填写地区名称');
                }
                $result = false;
                Db::startTrans();
                try {
                    if (isset($params['pid'])) {
                        if ($params['pid'] != $row['pid'] && $row['level'] != 4) {
                            // 数据迁移
                            if ($row['level'] == 2) {
                                // 更改的是市区
                                $save             = [];
                                $save['province'] = $params['pid'];
                                db('seller')->where(['city' => $row['id']])->update($save);
                            } else {
                                // 更改的是县区
                                $save['city']    = $params['pid'];
                                $new_province_id = db('area')->where(['id' => $params['pid']])->value('pid');
                                db('seller')->where(['district' => $row['id']])->update($save);
                            }

                        }
                    }
                    $result = db('area')->where(['id' => $row['id']])->update($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk    = $this->model->getPk();
            $list  = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $key => $value) {
                    $son = db('area')->where(['pid' => $value['id']])->count();
                    if ($son) {
                        Db::rollback();
                        $this->error('请先清空下级地区');
                    }
                    $area_id = $value['id'];
                    // $seller = db('seller')
                    // ->where(['province'=>$value['id']])
                    // ->whereOr(['city'=>$value['id']])
                    // ->whereOr(['district'=>$value['id']])
                    // ->count();
                    // if ( $seller ) {
                    //     Db::rollback();
                    //     $this->error('请先删除相关商家');
                    // }
                }
                foreach ($list as $k => $v) {
                    // $count += db('area')->where(['id'=>$v['id']])->delete();
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /*
    *选择城市，城市联动
     */
    public function select($value = '')
    {
        $type     = $this->request->get('type');
        $group_id = $this->request->get('group_id');
        $list     = null;
        if ($group_id !== '') {
            if ($type == 'province') {
                $list = db('area')->field('id as value, name')->where(['level' => 1, 'pid' => 0, 'deletetime' => null])->select();
            } else {
                $list = db('area')->field('id as value, name')->where(['pid' => $group_id, 'deletetime' => null])->select();
            }
        }
        $this->success('', null, $list);
    }

    /*
    *选择城市，城市联动
     */
    public function area($value = '')
    {
        $province = $this->request->get('province');
        $city     = $this->request->get('city');

        $area_one_id = $this->request->get('area_one_id');

        $where = [];

        $where['pid'] = 0;
        if ($province) {
            $where['pid'] = $province;
        }
        if ($city) {
            $where['pid'] = $city;
        }
        if ($area_one_id) {
            $where['pid'] = $area_one_id;
        }
        $where['deletetime'] = null;
        $list                = db('area')->field('id as value, name')->where($where)->select();
        $this->success('', null, $list);
    }

}
